package com.huiminpay.rocketmq.producer.message;

import com.huiminpay.rocketmq.producer.model.OrderExt;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ProducerSimple {

//    @Autowired
    @Resource
    RocketMQTemplate rocketMQTemplate;

    //发送同步消息
    public void sendSyncMsg(String topic,String msg){
        rocketMQTemplate.syncSend(topic,msg);
    }


    //发送异步消息
    public void sendASyncMsg(String topic,String msg){
        rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {

            //成功回调
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            //失败回调
            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }

    //发送自定义格式的消息
    public void sendMSgByJson(String topic, OrderExt orderExt){
        rocketMQTemplate.convertAndSend(topic,orderExt);
    }

    //发送延迟消息
    public void sendMSgByJsonDelay(String topic, OrderExt orderExt){
        Message<OrderExt> build = MessageBuilder.withPayload(orderExt).build();
        /*
        参数3  消息发送的超时时间
        参数4  消息的延迟等级 3  3代表-->10秒后发送
         */
        rocketMQTemplate.syncSend(topic,build,1000,3);
    }


}
